import React, { useState, useEffect } from "react";
import {
	Button,
	// Select, Input,
	Tooltip,
	DatePicker,
	Typography,
	message,
	Form,
	Row,
	Col,
	Space,
	Tag
} from "antd";
import { Input, Select, BatchSuffixInput } from "@/views/components/PrefixPlaceholder";
import { SwapLeftOutlined, SwapRightOutlined } from "@ant-design/icons";
import Iconfont from "@/components/IconFont";
import moment from "moment";
import { getAllArea } from "@/services/common";
import { logisticsCompanyList } from "@/utils/config";
import SelectAddress from "./component/SelectAddress";
import AreaSelect from "@/components/AreaSelect";
// import BatchSuffixInput from "@/views/components/BatchSuffixInput";
import WarehouseSelect from "@/views/components/WarehouseSelect"; // 导入WarehouseSelect组件
import {
	ClipboardText,
	CommonText,
	DownTime,
	EditAbleText,
	NumText,
	StatusText
} from "@/pages/OrderModule/common/components/CommonText";
import CommonTableSort from "@/views/components/CommonTableSort";
import SingleOrManySort from "./component/SingleOrManySort";
import SelectOrderTag from "@/views/components/SelectOrderTag";
import SelectShop from "@/views/components/SelectShop";
import {
	getLabelByValue,
	OUTBOUND_STATUS,
	OUTBOUND_LOGISTICS_STATUS,
	OUTBOUND_ORDERLABEL,
	OUTBOUND_PRINT_STATUS,
	OUTBOUND_REMAINING_DELIVERY_TIME,
	OUTBOUND_ORDER_GOODS_COUNT_STATUS
} from "@/views/utils/constant";
import { labelIconMap, labelNameMap } from "@/utils/config";

const { RangePicker } = DatePicker;
const { Text, Link } = Typography;
const dateFormat = "YYYY-MM-DD HH:mm:ss";
//选中的地址
let addressData = [];
// 物流状态下拉option
const expressStatusOptions = [
	{
		label: "无运单号",
		value: "0"
	},
	{
		label: "已获取运单号",
		value: "1"
	},
	{
		label: "正在获取运单号",
		value: "2"
	},
	{
		label: "运单号不足",
		value: "3"
	},
	{
		label: "接口报错",
		value: "4"
	},
	{
		label: "寄件人为空",
		value: "5"
	},
	{
		label: "未设置面单获取平台",
		value: "6"
	},
	{
		label: "运单号已取消",
		value: "12"
	}
];
export default ({
	type,
	setType,
	RefStoreList,
	RefErrorList,
	changeAddress,
	refOutboundTimeSort,
	refOrderCreationTimeSort,
	refGoodsCodeSort,
	fetchPage,
	handleOpenOrderDetailVisible,
	updateOrderRemarks
}) => {
	//订单标签
	const { Option } = Select;
	//省市区信息
	const [data, setData] = useState([]);
	// const [storeList, setStoreList] = useState([]); //店铺列表
	//仓库下拉列表
	// 所属仓库
	const [selectedWarehouse, setSelectedWarehouse] = useState(null);

	//
	// const [includeTagModalVisible, setIncludeTagModalVisible] = useState(false);
	//获取省市区地址信息
	const getAreaData = async () => {
		const { data, success } = await getAllArea();
		if (success) {
			// console.log("获取地址数据", data);
			setData(data);
		}
	};

	useEffect(() => {
		getAreaData();
		// getOrderLabels(); // 订单标签
		// getStoreList(); // 店铺
	}, [type]);
	// 所属仓库
	const handleWarehouseChange = value => {
		setSelectedWarehouse(value);
	};
	// 出库单状态选择
	const handleChangeStatus = value => {
		setType(value);
	};

	const SelectAddressProps = {
		handleChange(val) {
			changeAddress(val);
		}
	};

	const defaultColumns = [
		{
			name: "序号",
			code: "index",
			lock: true,
			render: (t, r, i) => i + 1,
			width: 60
		},
		{
			name: "出库单号",
			code: "outboundNo",
			render: (_, record) => (
				<Link
					onClick={() => {
						handleOpenOrderDetailVisible(record);
					}}
				>
					{record.outboundNo}
				</Link>
			),
			search: {
				content: () => (
					<BatchSuffixInput
						clearable
						allowClear
						autoMultiLine
						maxItem={500}
						modalProps={{
							title: "批量输入"
						}}
						placeholder="多个出库单号，以逗号隔开"
						message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
						areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
					/>
				)
			},

			width: 200
		},
		{
			name: "系统单号",
			code: "systemNo",
			render: (_, record) => (
				<Link
					onClick={() => {
						handleOpenOrderDetailVisible(record);
					}}
				>
					{record.systemNo}
				</Link>
			),
			search: {
				content: () => (
					<BatchSuffixInput
						clearable
						allowClear
						autoMultiLine
						modalProps={{
							title: "批量输入"
						}}
						maxItem={500}
						placeholder="多个系统单号，以逗号隔开"
						message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
						areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
					/>
				)
			},
			width: 200
		},
		{
			name: "店铺订单号",
			code: "shopOrderNo",
			search: {
				content: () => (
					<BatchSuffixInput
						clearable
						allowClear
						autoMultiLine
						maxItem={500}
						modalProps={{
							title: "批量输入"
						}}
						placeholder="店铺订单号"
						message="分行输入内容，提交后主页面输入框会按照逗号自动隔开，点击查询可批量查询。"
						areaPlaceholder="每行输入1个内容，最多500个，例如:&#10;1272572508553111112223&#10;1272572512332111112226"
					/>
				)
			},
			width: 200
		},
		{
			name: "供应商",
			code: "supplierName",
			search: { content: () => <Input placeholder="供应商" autoComplete="off" /> },
			hidden: true
		},
		{
			name: "出库单状态",
			code: "outboundStatus",
			render: (_, record) => (
				<StatusText
					as="s1"
					type={record.outboundStatus == "cancelled" ? "error" : record.outboundStatus == "shipped" ? "success" : "warning"}
					text={getLabelByValue(OUTBOUND_STATUS, record.outboundStatus)}
				/>
			),
			search: {
				formItemProps: {
					initialValue: type === "all" ? null : type
				},
				content: () => <Select placeholder="出库单状态" options={OUTBOUND_STATUS} onChange={handleChangeStatus} />
			},
			width: 100
		},
		{
			name: "出库单创建时间",
			title: () => (
				<CommonTableSort
					value={refOutboundTimeSort}
					title={"出库单创建时间"}
					onClick={order => {
						refGoodsCodeSort.current = null;
						refOutboundTimeSort.current = order;
						fetchPage();
					}}
				/>
			),
			code: "createTime",
			// features: { sortable: function () {} },
			width: 180,
			render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : "")
		},
		{
			name: "订单标签",
			code: "orderLabelArray",
			render: (text, record) => {
				return (
					<Space size={4}>
						{text?.map((item, idx) =>
							labelNameMap[item.labelId] ? (
								<Iconfont key={idx} type={labelIconMap[item.labelId]} style={{ fontSize: "16px" }} />
							) : (
								<Tag key={idx} color="#B1B7C3">
									{item.labelName}
								</Tag>
							)
						)}
					</Space>
				);
			},
			search: {
				code: "orderLabelIdList",
				order: 80,
				content: () => (
					<SelectOrderTag />
				)
			},
			width: 100
		},
		{
			name: "异常状态",
			code: "orderAbnormalStatus",
			search: {
				order: 130,
				content: () => (
					<Select showSearch placeholder="异常状态" allowClear>
						{RefErrorList.current.map(item => (
							<Option value={item.name} key={item.id}>
								<Tooltip title={item.name}>{item.name}</Tooltip>
							</Option>
						))}
					</Select>
				)
			},
			width: 100
		},
		{
			code: "consigneeDistrictCode",
			hidden: true,
			search: { order: 150, content: () => <AreaSelect {...SelectAddressProps} /> }
		},
		{
			name: "订单备注",
			code: "orderRemark",
			render: (_, record) => (
				<EditAbleText
					as="s1"
					text={record.orderRemark}
					onClick={() => {
						updateOrderRemarks({ record });
					}}
				/>
			),
			width: 100
		},
		{
			name: "买家留言",
			code: "buyerMessage",
			width: 100
		},
		{
			name: "卖家备注",
			code: "sellerMessage",
			width: 100
		},
		{
			hidden: true,
			search: {
				order: 160,
				group: [
					{
						span: 12,
						code: "remarkKey",
						formItemProps: {
							initialValue: "orderRemark"
						},
						content: () => (
							<Select origin="true" placeholder="订单备注" className="no-radius-l width-full">
								<Option value={"sellerMessage"}>卖家备注</Option>
								<Option value={"orderRemark"}>订单备注</Option>
								<Option value={"buyerMessage"}>买家留言</Option>
							</Select>
						)
					},
					{
						span: 12,
						code: "remarkVal",

						content: () => <Input origin="true" placeholder="关键字" className="no-radius-r" />
					}
				]
			}
		},
		{
			name: "快递公司",
			code: "expressCompany",
			width: 160,
			render: (_, record) => (
				<>
					<p>{record.expressCompany}</p>
					<span>{record.waybillNo}</span>
				</>
			),
			search: {
				order: 90,
				content: () => (
					<Select placeholder="快递公司" allowClear mode="tags">
						{logisticsCompanyList.map((item, index) => (
							<Option key={index} value={item}>
								{item}
							</Option>
						))}
					</Select>
				)
			}
		},
		{
			name: "快递物流单号",
			code: "waybillNo",

			search: { order: 100, content: () => <Input placeholder="快递物流单号" autoComplete="off" /> },
			hidden: true
		},
		{
			name: "物流状态",
			code: "expressStatus",
			hidden: true,
			search: {
				order: 110,
				content: () => <Select placeholder="物流状态" options={expressStatusOptions} allowClear />
			}
		},
		{
			name: "快递单打印",
			code: "expressPrintStatus",
			render: (_, record) => <>{getLabelByValue(OUTBOUND_PRINT_STATUS, record.expressPrintStatus)}</>,
			search: {
				order: 120,
				content: () => <Select placeholder="打印状态" options={OUTBOUND_PRINT_STATUS} allowClear />
			},
			width: 100
		},
		{
			name: "采购额",
			code: "orderPrice",
			width: 100,
			render: value => <NumText type="error" as="s1" pre={value ? "¥ " : ""} num={value} useBold />
		},
		{
			name: "收件信息",
			code: "reciverName",
			width: 320,
			render: (_, record) => {
				return `${record.consignee} ${record.consigneePhone} ${record.consigneeDistrict} ${record.consigneeAddress}`;
			},
			search: {
				order: 140,
				group: [
					{
						span: 12,
						code: "consigneeKey",
						formItemProps: {
							initialValue: "consignee"
						},
						content: () => (
							<Select origin="true" placeholder="收件人地址" className="no-radius-l width-full">
								<Option value="consignee">收件人姓名</Option>
								<Option value="consigneePhone">收件人电话</Option>
								<Option value="consigneeAddress">收件人地址</Option>
							</Select>
						)
					},
					{
						span: 12,
						code: "consigneeVal",

						content: () => <Input origin="true" placeholder="关键字" autoComplete="off" className="no-radius-r" />
					}
				]
			}
		},
		{
			name: "商品编码*数量",
			title: () => (
				<SingleOrManySort
					value={refGoodsCodeSort}
					title="商品编码*数量"
					onClick={order => {
						refOutboundTimeSort.current = null;
						refOrderCreationTimeSort.current = null;
						refGoodsCodeSort.current = order;
						fetchPage();
					}}
				/>
			),
			// name: "商品编码*数量",
			code: "skuCode",
			width: 240,
			render: (_, record) => {
				const count = record?.outboundProductList?.reduce((pre, cur) => {
					return pre + cur.skuQuantity;
				}, 0);

				return (
					<>
						{!!count && count + "，"}
						{record?.outboundProductList
							?.map(item => {
								return item.skuCode + " * " + item.skuQuantity;
							})
							.join("；")}
					</>
				);
			},
			search: { order: 60, content: () => <Input placeholder="商品编码" autoComplete="off" /> }
		},
		{
			name: "订单商品数量",
			code: "oneProductFlag",

			hidden: true,
			search: {
				order: 70,
				content: () => <Select options={OUTBOUND_ORDER_GOODS_COUNT_STATUS} placeholder="订单商品数量" allowClear />
			}
		},
		{
			name: "预估重量",
			code: "estimatedWeight",
			width: 100
		},
		{
			name: "实际重量",
			code: "actualWeight",
			width: 100
		},
		{
			name: "拿货完成时间",
			code: "pickingCompleteTime",
			width: 180,
			render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : "")
		},
		{
			name: "出库时间",
			code: "outboundTime",
			width: 180,
			render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : "")
		},
		{
			name: "下单店铺",
			code: "shop",
			width: 180,
			search: {
				order: 170,
				code: "shop",
				content: () => (
					<Select showSearch placeholder="下单店铺" allowClear>
						{RefStoreList.current.map(item => (
							<Option value={item.systemStoreName || item.storeName} key={item.storeId}>
								<Tooltip title={item.systemStoreName || item.storeName}>{item.systemStoreName || item.storeName}</Tooltip>
							</Option>
						))}
					</Select>
				)
			}
		},
		{
			name: "店铺订单创建时间",
			title: () => (
				<CommonTableSort
					value={refOrderCreationTimeSort}
					title={"店铺订单创建时间"}
					onClick={order => {
						refGoodsCodeSort.current = null;
						refOrderCreationTimeSort.current = order;
						fetchPage();
					}}
				/>
			),
			code: "orderCreationTime",
			width: 180,
			render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
			search: {
				order: 170,
				code: "remainingDeliveryTimeFlag",
				content: () => <Select placeholder="剩余发货时间" options={OUTBOUND_REMAINING_DELIVERY_TIME} allowClear />
			}
		},
		{
			name: "平台最晚发货时间",
			code: "latestDeliveryTime",
			width: 180,
			render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : "")
		},
		// {
		// 	name: "剩余发货时间",
		// 	code: "spickingCompleteTimeType",
		// },
		{
			hidden: true,
			search: {
				order: 180,
				span: 6,
				group: [
					{
						span: 6,
						code: "timeType",
						formItemProps: {
							initialValue: 1
						},
						content: () => (
							<Select origin="true" placeholder="出库单创建时间" allowClear className="no-radius-l">
								<Option value={1}>出库单创建时间</Option>
								<Option value={2}>出库单出库时间</Option>
								<Option value={3}>平台最晚发货时间</Option>
								<Option value={4}>店铺订单创建时间</Option>
							</Select>
						)
					},
					{
						keys: ["startTime", "endTime"],
						span: 18,
						code: "time",
						content: () => <RangePicker format={dateFormat} showTime className="no-radius-r" />
					}
				]
			}
		},
		{
			name: "所属仓库",
			code: "warehouseName",
			width: 120,
			search: {
				order: 200,
				code: "warehouseId",
				content: () => {
					return <WarehouseSelect value={selectedWarehouse} placeholder={"所属仓库"} onChange={handleWarehouseChange} />;
				}
			}
		},
		{
			name: "操作",
			code: "action",
			align: "center",
			width: 80,
			lock: true,
			render: (_, record) => (
				<Button type="link" onClick={() => handleOpenOrderDetailVisible(record)}>
					详情
				</Button>
			)
		}
	];
	return { defaultColumns };
};
